package com.csdj.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csdj.server.conflg.JwtTokenUtil;
import com.csdj.server.mapper.AdminMapper;
import com.csdj.server.mapper.AdminRoleMapper;
import com.csdj.server.mapper.RoleMapper;
import com.csdj.server.pojo.Admin;
import com.csdj.server.pojo.AdminRole;
import com.csdj.server.pojo.RespBean;
import com.csdj.server.pojo.Role;
import com.csdj.server.service.IAdminService;
import com.csdj.server.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xyx
 * @since 2022-12-12
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired(required = false)
    private AdminMapper adminMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil tokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Autowired(required = false)
    private AdminRoleMapper adminRoleMapper;

    @Override
    public RespBean login(String username, String password,String code, HttpServletRequest request) {
        //security
        String captcha = (String)request.getSession().getAttribute("captcha");
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //如果验证码为空 或者 输入的验证码不一致 就回执信息
        if(StringUtils.isBlank(captcha) || !captcha.equals(code)) {
            return RespBean.error("验证码错误!");
        }
        //判断加密密码和输入密码是否一致 通过security获取用户信息
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("账号或者密码错误!");
        }
        //判断账号是否被禁用
        if(!userDetails.isEnabled()){
            return RespBean.error("该账号被封禁,请联系管理员");
        }
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        //拿到一个全局的 securityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        String token = tokenUtil.genratToken(userDetails);
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("token",token);
        map.put("tokenHead",tokenHead);
        return RespBean.success("登陆成功",map);
    }

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    @Override
    public Admin getAdminInfoByUserName(String username) {
        //select * from admin where username = "admin"
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username));
    }

    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    @Override
    public List<Admin> getAllAdmins(String keywords) {
        //id 怎么获取 可以从 Security全局对象中获取
/*        Integer id = ((Admin) SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal())
                .getId();*/
        return adminMapper.getAllAdmins(AdminUtils.getCurrentAdmin().getId(),keywords);
    }

    /**
     * 操作员 更改 角色信息
     * @param adminId
     * @param rids
     * @return
     */
    @Override
    public RespBean updateAdminRole(Integer adminId, Integer[] rids) {
        // 1.需要把原有的当前用户的 角色信息 先做删除
        adminRoleMapper.delete(new QueryWrapper<AdminRole>()
                .eq("adminId",adminId));
        //2.删除之后 添加新的角色信息
        Integer result = adminRoleMapper.addRole(adminId, rids);
        if(result==rids.length){
            return RespBean.success("修改成功!");
        }
        return RespBean.error("修改失败!");
    }
}
